package com.newenergy.wisehome.ui.fragment;


import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.util.LocaleUtil;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.data.bean.BallLight;
import com.newenergy.wisehome.data.bean.DeviceCategory;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.ormlite.dao.BallLightDao;
import com.newenergy.wisehome.data.ormlite.dao.DeviceCategoryDao;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.ui.adapter.IconAdapter;
import com.newenergy.wisehome.ui.adapter.RoomAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.ISupportFragment;

/**
 * 组(房间)列表
 */
public class GroupListFragment extends BaseFragment {

    private static String ARG_GROUPLIST = "arg_grouplist";
    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.tv_back)
    TextView mTvBack;
    @BindView(R.id.tv_page)
    TextView mTvPage;
    @BindView(R.id.btn_add)
    Button mBtnAdd;
    @BindView(R.id.btn_edit)
    Button mBtnEdit;
    @BindView(R.id.btn_add_room)
    Button mBtnAddRoom;
    @BindView(R.id.recyclerView)
    EasyRecyclerView mRecyclerView;
    @BindView(R.id.view)
    View mView;
    @BindView(R.id.tv_empty)
    TextView mTvEmpty;
    @BindView(R.id.rl_empty)
    RelativeLayout mRlEmpty;

    private RoomAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;

    private Family mCurrFamily;
    private int mGroupPosition = 0;
    private DeviceCategory mGroup;

    private Dialog mEditDialog;
    private PopupWindow mPopupWindow;
    private EasyRecyclerView mIconRecyclerView;
    private IconAdapter mIconAdapter;
    private BallLight mBallLight;
    private int confirmType = 1;
    private TextView mTv_tip;


    public GroupListFragment() {

    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_group_list;
    }


    public static ISupportFragment newInstace(Family currFamily) {
        Bundle args = new Bundle();
        args.putParcelable(ARG_GROUPLIST, currFamily);
        GroupListFragment fragment = new GroupListFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void init(View rootView) {
        initRecycleView();
        mCurrFamily = getArguments().getParcelable(ARG_GROUPLIST);
        if (mCurrFamily == null) {
            mTvPage.setText(getString(R.string.no_family));
            mBtnAddRoom.setVisibility(View.INVISIBLE);
            return;
        }
        mTvPage.setText(mCurrFamily.getName());
        if (mCurrFamily.getType() != 0) {
            mBtnAddRoom.setVisibility(View.VISIBLE);
        } else {
            mBtnAddRoom.setVisibility(View.INVISIBLE);
        }
        mAdapter.type = mCurrFamily.getType();
        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
        List<DeviceCategory> groups = new ArrayList<>();

        /*BallLight ballLight =new BallLight("12345678",1,"00",getString(R.string.default_device),"ce shi zu","bg_all_device_n");
        DeviceCategory deviceCategory = ballLight.covertToDeviceCategory();*/
        BallLight defaultGroup = AppManager.getInstance(getContext()).mDefaultBallLight;
        DeviceCategory deviceCategory = defaultGroup.covertToDeviceCategory();
        groups.add(deviceCategory);

        groups.addAll(deviceCategoryDao.getFamilyLighting(mCurrFamily.getFamilyId()));

        mAdapter.refreshData(groups);
        setCurrItem();
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
            List<DeviceCategory> groups = new ArrayList<>();

            BallLight defaultGroup = AppManager.getInstance(getContext()).mDefaultBallLight;
            DeviceCategory deviceCategory = defaultGroup.covertToDeviceCategory();
            groups.add(deviceCategory);

            groups.addAll(deviceCategoryDao.getFamilyLighting(mCurrFamily.getFamilyId()));

            mAdapter.refreshData(groups);
            setCurrItem();
        }
    }


    private void setCurrItem() {
        List<DeviceCategory> deviceCategoryList = mAdapter.getAllData();
        if (deviceCategoryList == null || deviceCategoryList.size() < 1) {
            mGroupPosition = 0;
            mGroup = null;
            AppManager.getInstance(getContext()).selectGroup = null;
            mRlEmpty.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
            mTvEmpty.setText(R.string.add_lighting_first);//"当前家庭还没有添加照明设备！"
            return;
        }

        for (DeviceCategory group : deviceCategoryList) {
            group.setChecked(false);
        }

        mRecyclerView.setVisibility(View.VISIBLE);
        mRlEmpty.setVisibility(View.GONE);
        mGroup = deviceCategoryList.get(mGroupPosition);
        mGroup.setChecked(true);
        mAdapter.notifyDataSetChanged();
        if (mGroup.getCategory() == 1) {
            BallLightDao ballLightDao = new BallLightDao(getContext());
            mBallLight = ballLightDao.getByUuid(mGroup.getUuid());
        }
    }


    private void initRecycleView() {
        Context context = getContext();
        mAdapter = new RoomAdapter(context);
        mRecyclerView.setAdapter(mAdapter);
        mLayoutManager = new LinearLayoutManager(context);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter.setOnItemClickListener(position -> {
            mGroupPosition = position;
            setCurrItem();
        });

        mAdapter.setItemEditCallBack(new RoomAdapter.ItemEditCallBack() {
            @Override
            public void notifyPage(int position) {
                mGroupPosition = position;
                mGroup = mAdapter.getItem(mGroupPosition);
                setCurrItem();
                showEditDialog();
            }
        });


        mAdapter.setItemOperCallBack(new RoomAdapter.ItemOperCallBack() {

            @Override
            public void notifyAdd(int position) {
                confirmType = 1;
                mGroup = mAdapter.getItem(position);
                String msg = getString(R.string.open_before_add);
                showConfirmDialog(msg);
            }


            @Override
            public void notifyDelete(int position) {
                confirmType = 2;
                mGroup = mAdapter.getItem(position);

                String msg = getString(R.string.open_before_deleting_device);
                showConfirmDialog(msg);
            }


          /*  @Override
            public void notifyForceDelete(int position) {
                confirmType = 3;
                mGroup = mAdapter.getItem(position);
                String msg = getString(R.string.sure_force_delete);
                showConfirmDialog(msg);
            }*/

        });

    }


    @OnClick({R.id.btn_back, R.id.tv_back, R.id.btn_add_room})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;
            case R.id.tv_back:
                doBack();
                break;
            case R.id.btn_add_room:
                start(CreateGroupFramgment.newInstance(mCurrFamily));
//                showBottomDialog();
                break;
        }
    }

    public void showBottomDialog() {
        View contenView = View.inflate(getContext(), R.layout.dialog_add_group, null);
        final Dialog dialog = new Dialog(getContext(), R.style.style_dialog);

        Button addBallLight = (Button) contenView.findViewById(R.id.btn_add_ballLight);

        Button cancel = (Button) contenView.findViewById(R.id.btn_cancel);
        dialog.setContentView(contenView);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        dialog.show();
        addBallLight.setOnClickListener(v -> {
            dialog.dismiss();
            start(CreateGroupFramgment.newInstance(mCurrFamily));
        });

        cancel.setOnClickListener(v -> {
            dialog.dismiss();

        });
    }


    private void deleteGroup() {
        if (mCurrFamily.getType() != 0) {
            if (mGroup.getCategory() == 1) {
                AppManager.getInstance(mainActivity).notifyDeleteGroup(mBallLight);
            }
        }

        BallLightDao ballLightDao = new BallLightDao(getContext());
        ballLightDao.delete(mBallLight);
        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
        //删除远程设备
        BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
        familyManager.delBLDevice(mCurrFamily, mGroup);
        deviceCategoryDao.delete(mGroup);
        mAdapter.remove(mGroup);
        mGroupPosition = 0;
//        myToast(getString(R.string.delete) + mGroup.getName() + getString(R.string.success), false);
        setCurrItem();
    }


    private void showEditDialog() {
        mEditDialog = new Dialog(getContext(), R.style.CustomDialog);
        View contentView = View.inflate(getContext(), R.layout.dialog_edit_group, null);
        mEditDialog.setContentView(contentView);
        EditText et_name = (EditText) contentView.findViewById(R.id.et_name);

        Button btn_delete = (Button) contentView.findViewById(R.id.btn_delete);

        Button btn_select_icon = (Button) contentView.findViewById(R.id.btn_select_icon);

        Button btn_confirm = (Button) contentView.findViewById(R.id.btn_confirm);

        Button btn_cancel = (Button) contentView.findViewById(R.id.btn_cancel);

        mTv_tip = (TextView) contentView.findViewById(R.id.tv_tip);

        btn_select_icon.setVisibility(View.GONE);
        String groupName = mGroup.getName();
        et_name.setText(groupName);
        et_name.setSelection(groupName.length());

        if (mGroup.getFamilyId().equals("12345678") && mGroup.getGroupId().equals("01")) {
            btn_delete.setVisibility(View.INVISIBLE);
        } else {
            btn_delete.setVisibility(View.VISIBLE);
        }

        mEditDialog.show();
        btn_delete.setOnClickListener(v -> {
            mEditDialog.dismiss();
            String msg = getString(R.string.sure_delete) + mGroup.getName() + getString(R.string.open_before_deleting);
            confirmType = 4;
            showConfirmDialog(msg);
        });

        btn_select_icon.setOnClickListener(v -> {
            showPopupWindow(et_name);
        });

        btn_confirm.setOnClickListener(v -> {

            String name = et_name.getText().toString().trim();
            updateGroupName(name);
            DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
            deviceCategoryDao.updateDeviceCategory(mGroup);
            if (mGroup.getCategory() == 1) {

                BallLightDao ballLightDao = new BallLightDao(getContext());
                ballLightDao.updateBallLight(mBallLight);
            }
            setCurrItem();

        });
        btn_cancel.setOnClickListener(v -> {
            mEditDialog.dismiss();
        });
    }


    public void showPopupWindow(View dropView) {
        mPopupWindow = new PopupWindow(mIconRecyclerView, dpToPx(200), dpToPx(150));
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(false);
        mPopupWindow.setFocusable(true);
        mPopupWindow.showAsDropDown(dropView, -dpToPx(20), dpToPx(3));
    }

    private void updateGroupName(String name) {

        if (mGroup.getName().equals(name)) {
            mEditDialog.dismiss();
            mEditDialog = null;
            return;
        }

       /* boolean isOk = checkGroupName(name);

        if (!isOk) return;
        */
        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
        if (TextUtils.isEmpty(name)) {
//            myToast(getString(R.string.tip_room_name_nonull), true);
            mTv_tip.setText(getString(R.string.tip_room_name_nonull));
            return;
        }

        if (LocaleUtil.getLanguage().startsWith("zh")) {
            if (name.length() < 2 || name.length() > 10) {
//                ToastUtil.myToast(getString(R.string.tip_room_name_range), true);
                mTv_tip.setText(getString(R.string.tip_room_name_range));
                return;
            }

        } else {
            if (name.length() < 1) {
//                ToastUtil.myToast(getString(R.string.tip_room_name_range), true);
                mTv_tip.setText(getString(R.string.tip_room_name_range));
                return;
            }
        }


        if (name.contains("[") || name.contains("#") || name
                .contains("&")) {
//            ToastUtil.myToast(getString(R.string.tip_room_name_error), true);
            mTv_tip.setText(getString(R.string.tip_room_name_error));
            return;
        }

        if (mCurrFamily == null) return;
        DeviceCategory group = deviceCategoryDao.getDeviceCategoryByName(mCurrFamily.getFamilyId(), name);
        if (group != null) {
//            myToast(getString(R.string.tip_room_name_used), true);
            mTv_tip.setText(getString(R.string.tip_room_name_used));
            return;
        }

        mGroup.setName(name);
        if (mGroup.getCategory() == 1) {
            mBallLight.setName(name);
        }

        try {
            String pinyinString = PinyinHelper.convertToPinyinString(name, " ", PinyinFormat.WITHOUT_TONE);
            mGroup.setPingyinName(pinyinString);
            if (mGroup.getCategory() == 1) {
                mBallLight.setPingyinName(pinyinString);
            }

        } catch (PinyinException e) {
            e.printStackTrace();
        }

        mEditDialog.dismiss();
        mEditDialog = null;
    }


    @Override
    protected void confirmOperation() {
        AppManager appManager = AppManager.getInstance(mainActivity);
        appManager.mSelectDeviceCategory = mGroup;
        if (confirmType == 1) {//设置组
            if (mGroup.getCategory() == 1) {
                BallLightDao ballLightDao = new BallLightDao(getContext());
                mBallLight = ballLightDao.getByUuid(mGroup.getUuid());
                appManager.notifyAddGroup(mBallLight);
            }

        } else if (confirmType == 2) {//删除组
            if (mGroup.getCategory() == 1) {
                BallLightDao ballLightDao = new BallLightDao(getContext());
                mBallLight = ballLightDao.getByUuid(mGroup.getUuid());
                appManager.notifyDeleteGroup(mBallLight);
            }

        } /*else if (confirmType == 3) {
            if (mGroup.getCategory() == 1) {
                AppManager.getInstance(mainActivity).commandAdvertise("F0", "12345678", "01", "00000000", "000001", 73, 4777, 2, "7201");
            }
        }*/ else if (confirmType == 4) {
            deleteGroup();
        }

    }

}
